// 测验页面JavaScript功能

let currentTest = null;
let currentQuestionIndex = 0;
let questions = [];
let userAnswers = [];
let selectedAnswer = null;

// 开始测验
function startTest(wordType) {
    currentTest = wordType;
    currentQuestionIndex = 0;
    userAnswers = [];
    selectedAnswer = null;
    
    // 准备题目
    if (wordType === 'all') {
        questions = [...questionBank['就'], ...questionBank['假']];
    } else {
        questions = [...questionBank[wordType]];
    }
    
    // 打乱题目顺序
    questions = shuffleArray(questions);
    
    // 隐藏选择页面，显示测验页面
    document.getElementById('test-selection').classList.add('hidden');
    document.getElementById('test-progress').classList.remove('hidden');
    
    // 更新总题数
    document.getElementById('total-questions').textContent = questions.length;
    
    // 显示第一题
    showQuestion();
}

// 打乱数组
function shuffleArray(array) {
    const newArray = [...array];
    for (let i = newArray.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
    }
    return newArray;
}

// 显示题目
function showQuestion() {
    const question = questions[currentQuestionIndex];
    
    // 更新进度
    updateProgress();
    
    // 更新题目编号
    document.getElementById('current-question').textContent = currentQuestionIndex + 1;
    
    // 显示题目
    document.getElementById('question-text').textContent = question.question;
    
    // 显示选项
    const optionsContainer = document.getElementById('options-container');
    optionsContainer.innerHTML = '';
    
    question.options.forEach((option, index) => {
        const optionDiv = document.createElement('div');
        optionDiv.className = 'option';
        optionDiv.textContent = option;
        optionDiv.onclick = () => selectOption(index, optionDiv);
        optionsContainer.appendChild(optionDiv);
    });
    
    // 重置选择状态
    selectedAnswer = null;
    document.getElementById('next-btn').disabled = true;
    document.getElementById('next-btn').textContent = 
        currentQuestionIndex === questions.length - 1 ? '完成测验' : '下一题';
}

// 选择选项
function selectOption(index, optionElement) {
    // 清除之前的选择
    document.querySelectorAll('.option').forEach(opt => {
        opt.classList.remove('selected');
    });
    
    // 标记当前选择
    optionElement.classList.add('selected');
    selectedAnswer = index;
    
    // 启用下一题按钮
    document.getElementById('next-btn').disabled = false;
}

// 下一题
function nextQuestion() {
    if (selectedAnswer === null) return;
    
    // 记录答案
    userAnswers.push(selectedAnswer);
    
    // 显示正确答案
    showCorrectAnswer();
    
    // 延迟后进入下一题或结束测验
    setTimeout(() => {
        currentQuestionIndex++;
        if (currentQuestionIndex < questions.length) {
            showQuestion();
        } else {
            showResult();
        }
    }, 1500);
}

// 显示正确答案
function showCorrectAnswer() {
    const question = questions[currentQuestionIndex];
    const options = document.querySelectorAll('.option');
    
    options.forEach((option, index) => {
        if (index === question.correct) {
            option.classList.add('correct');
        } else if (index === selectedAnswer && index !== question.correct) {
            option.classList.add('incorrect');
        }
        option.onclick = null; // 禁用点击
    });
    
    document.getElementById('next-btn').disabled = true;
}

// 更新进度条
function updateProgress() {
    const progress = ((currentQuestionIndex + 1) / questions.length) * 100;
    document.getElementById('progress-fill').style.width = progress + '%';
}

// 显示测验结果
function showResult() {
    // 隐藏测验页面，显示结果页面
    document.getElementById('test-progress').classList.add('hidden');
    document.getElementById('test-result').classList.remove('hidden');
    
    // 计算分数
    let correctCount = 0;
    userAnswers.forEach((answer, index) => {
        if (answer === questions[index].correct) {
            correctCount++;
        }
    });
    
    const percentage = Math.round((correctCount / questions.length) * 100);
    
    // 显示分数
    document.getElementById('score-percentage').textContent = percentage + '%';
    document.getElementById('correct-count').textContent = correctCount;
    document.getElementById('total-count').textContent = questions.length;
    
    // 显示详细结果
    showDetailedResults(correctCount);
}

// 显示详细结果
function showDetailedResults(correctCount) {
    const resultDetails = document.getElementById('result-details');
    let detailsHTML = '';
    
    questions.forEach((question, index) => {
        const userAnswer = userAnswers[index];
        const isCorrect = userAnswer === question.correct;
        
        detailsHTML += `
            <div class="result-item ${isCorrect ? 'correct' : 'incorrect'}">
                <h4>第${index + 1}题</h4>
                <p><strong>题目：</strong>${question.question}</p>
                <p><strong>你的答案：</strong><span class="${isCorrect ? 'correct-answer' : 'user-answer'}">${question.options[userAnswer]}</span></p>
                ${!isCorrect ? `<p><strong>正确答案：</strong><span class="correct-answer">${question.options[question.correct]}</span></p>` : ''}
                <p><strong>解析：</strong>${question.explanation}</p>
            </div>
        `;
    });
    
    resultDetails.innerHTML = detailsHTML;
}

// 重新测验
function retryTest() {
    if (currentTest) {
        // 隐藏结果页面
        document.getElementById('test-result').classList.add('hidden');
        
        // 重新开始相同的测验
        startTest(currentTest);
    }
}

// 返回主页
function goHome() {
    window.location.href = '../index.html';
}

// 去复习
function goToReview() {
    window.location.href = 'review.html';
}

// 返回选择页面
function backToSelection() {
    // 隐藏所有页面
    document.getElementById('test-progress').classList.add('hidden');
    document.getElementById('test-result').classList.add('hidden');
    document.getElementById('practice-article').classList.add('hidden');
    document.getElementById('practice-test').classList.add('hidden');
    document.getElementById('practice-result').classList.add('hidden');
    
    // 显示选择页面
    document.getElementById('test-selection').classList.remove('hidden');
}

// 模拟题练习相关变量
let currentPracticeData = null;
let currentPracticeQuestionIndex = 0;
let practiceQuestions = [];
let practiceUserAnswers = [];
let practiceSelectedAnswer = null;
let practiceTimer = null;
let practiceTimeLeft = 1200; // 20分钟 = 1200秒
let practiceStartTime = null;

// 显示模拟题文章
function showPracticeArticle(articleId) {
    currentPracticeData = practiceData[articleId];
    
    // 隐藏选择页面
    document.getElementById('test-selection').classList.add('hidden');
    
    // 显示文章页面
    document.getElementById('practice-article').classList.remove('hidden');
    
    // 更新文章内容
    document.getElementById('article-title').textContent = currentPracticeData.title;
    document.querySelector('.article-author').textContent = currentPracticeData.author + ' · ' + currentPracticeData.dynasty;
    
    // 显示文章内容，将\n转换为换行
    const articleText = currentPracticeData.content.replace(/\n/g, '\n');
    document.getElementById('article-text').textContent = articleText;
}

// 开始模拟题练习（新的左右布局）
function startPracticeTest() {
    if (!currentPracticeData) return;
    
    // 初始化练习数据
    currentPracticeQuestionIndex = 0;
    practiceQuestions = [...currentPracticeData.questions];
    practiceUserAnswers = new Array(practiceQuestions.length).fill(null);
    practiceSelectedAnswer = null;
    practiceTimeLeft = 1200; // 重置为20分钟
    practiceStartTime = Date.now();
    
    // 隐藏文章页面，显示左右布局页面
    document.getElementById('practice-article').classList.add('hidden');
    document.getElementById('practice-layout').classList.remove('hidden');
    
    // 设置文章内容到左侧面板
    document.getElementById('article-title-inline').textContent = currentPracticeData.title;
    document.getElementById('article-author-inline').textContent = currentPracticeData.author + ' · ' + currentPracticeData.dynasty;
    
    // 显示文章内容，保持换行格式
    const articleText = currentPracticeData.content.replace(/\n/g, '\n');
    document.getElementById('article-content-inline').textContent = articleText;
    
    // 更新总题数
    document.getElementById('layout-total-questions').textContent = practiceQuestions.length;
    
    // 开始计时器
    startPracticeTimer();
    
    // 显示第一题
    showLayoutQuestion();
}

// 开始计时器
function startPracticeTimer() {
    if (practiceTimer) {
        clearInterval(practiceTimer);
    }
    
    practiceTimer = setInterval(() => {
        practiceTimeLeft--;
        updateTimerDisplay();
        
        if (practiceTimeLeft <= 0) {
            clearInterval(practiceTimer);
            // 时间到，自动提交
            finishPracticeTest();
        }
    }, 1000);
}

// 更新计时器显示
function updateTimerDisplay() {
    const minutes = Math.floor(practiceTimeLeft / 60);
    const seconds = practiceTimeLeft % 60;
    const timeString = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    
    const timerDisplay = document.getElementById('timer-display');
    timerDisplay.textContent = timeString;
    
    // 根据剩余时间改变样式
    timerDisplay.className = 'timer-display';
    if (practiceTimeLeft <= 300) { // 5分钟以下
        timerDisplay.classList.add('danger');
    } else if (practiceTimeLeft <= 600) { // 10分钟以下
        timerDisplay.classList.add('warning');
    }
}

// 显示左右布局题目
function showLayoutQuestion() {
    const question = practiceQuestions[currentPracticeQuestionIndex];
    
    // 更新题目编号
    document.getElementById('layout-current-question').textContent = currentPracticeQuestionIndex + 1;
    
    // 显示题目
    document.getElementById('layout-question-text').textContent = question.question;
    
    // 根据题目类型显示不同内容
    if (question.type === 'choice') {
        // 选择题
        document.getElementById('layout-question-options').classList.remove('hidden');
        document.getElementById('layout-translation-question').classList.add('hidden');
        
        // 显示选项
        const optionsContainer = document.getElementById('layout-question-options');
        optionsContainer.innerHTML = '';
        
        question.options.forEach((option, index) => {
            const optionDiv = document.createElement('div');
            optionDiv.className = 'question-option';
            optionDiv.textContent = option;
            optionDiv.onclick = () => selectLayoutOption(index, optionDiv);
            
            // 如果已经选择过，恢复选择状态
            if (practiceUserAnswers[currentPracticeQuestionIndex] === index) {
                optionDiv.classList.add('selected');
                practiceSelectedAnswer = index;
            }
            
            optionsContainer.appendChild(optionDiv);
        });
    } else if (question.type === 'translation') {
        // 翻译题
        document.getElementById('layout-question-options').classList.add('hidden');
        document.getElementById('layout-translation-question').classList.remove('hidden');
        
        // 显示翻译题内容
        document.getElementById('layout-translation-text').textContent = question.question;
        document.getElementById('layout-translation-answer-text').textContent = question.answer;
        document.getElementById('layout-translation-explanation').textContent = question.explanation;
        
        // 翻译题自动标记为已答
        practiceSelectedAnswer = 0;
        practiceUserAnswers[currentPracticeQuestionIndex] = 0;
    }
    
    // 更新按钮状态
    updateLayoutButtons();
}

// 选择左右布局选项
function selectLayoutOption(index, optionElement) {
    // 清除之前的选择
    document.querySelectorAll('#layout-question-options .question-option').forEach(opt => {
        opt.classList.remove('selected');
    });
    
    // 标记当前选择
    optionElement.classList.add('selected');
    practiceSelectedAnswer = index;
    
    // 记录答案
    practiceUserAnswers[currentPracticeQuestionIndex] = index;
    
    // 更新按钮状态
    updateLayoutButtons();
}

// 更新左右布局按钮状态
function updateLayoutButtons() {
    const prevBtn = document.getElementById('layout-prev-btn');
    const nextBtn = document.getElementById('layout-next-btn');
    
    // 上一题按钮
    prevBtn.disabled = currentPracticeQuestionIndex === 0;
    
    // 下一题按钮
    const isAnswered = practiceUserAnswers[currentPracticeQuestionIndex] !== null;
    nextBtn.disabled = !isAnswered;
    
    // 最后一题时显示"完成练习"
    if (currentPracticeQuestionIndex === practiceQuestions.length - 1) {
        nextBtn.textContent = '完成练习';
        nextBtn.className = 'question-nav-btn finish';
    } else {
        nextBtn.textContent = '下一题';
        nextBtn.className = 'question-nav-btn next';
    }
}

// 上一题
function prevLayoutQuestion() {
    if (currentPracticeQuestionIndex > 0) {
        currentPracticeQuestionIndex--;
        practiceSelectedAnswer = practiceUserAnswers[currentPracticeQuestionIndex];
        showLayoutQuestion();
    }
}

// 下一题
function nextLayoutQuestion() {
    if (currentPracticeQuestionIndex < practiceQuestions.length - 1) {
        currentPracticeQuestionIndex++;
        practiceSelectedAnswer = practiceUserAnswers[currentPracticeQuestionIndex];
        showLayoutQuestion();
    } else {
        // 完成练习
        finishPracticeTest();
    }
}

// 完成练习测试
function finishPracticeTest() {
    // 停止计时器
    if (practiceTimer) {
        clearInterval(practiceTimer);
        practiceTimer = null;
    }
    
    // 隐藏左右布局页面，显示结果页面
    document.getElementById('practice-layout').classList.add('hidden');
    document.getElementById('practice-result').classList.remove('hidden');
    
    // 计算分数
    let totalScore = 0;
    let maxScore = 0;
    let choiceScore = 0;
    let choiceMaxScore = 0;
    let translationScore = 0;
    let translationMaxScore = 0;
    
    practiceQuestions.forEach((question, index) => {
        const userAnswer = practiceUserAnswers[index];
        maxScore += question.score;
        
        if (question.type === 'choice') {
            choiceMaxScore += question.score;
            if (userAnswer === question.correct) {
                totalScore += question.score;
                choiceScore += question.score;
            }
        } else if (question.type === 'translation') {
            translationMaxScore += question.score;
            // 翻译题给满分（学生自己对照答案）
            totalScore += question.score;
            translationScore += question.score;
        }
    });
    
    const percentage = Math.round((totalScore / maxScore) * 100);
    
    // 显示分数
    document.getElementById('practice-score-percentage').textContent = percentage + '%';
    document.getElementById('practice-total-score').textContent = totalScore;
    document.getElementById('practice-max-score').textContent = maxScore;
    document.getElementById('practice-choice-score').textContent = choiceScore;
    document.getElementById('practice-choice-max').textContent = choiceMaxScore;
    document.getElementById('practice-translation-score').textContent = translationScore;
    document.getElementById('practice-translation-max').textContent = translationMaxScore;
    
    // 显示详细结果
    showLayoutDetailedResults();
}

// 显示详细结果
function showLayoutDetailedResults() {
    const resultDetails = document.getElementById('practice-result-details');
    let detailsHTML = '';
    
    practiceQuestions.forEach((question, index) => {
        const userAnswer = practiceUserAnswers[index];
        
        if (question.type === 'choice') {
            const isCorrect = userAnswer === question.correct;
            
            detailsHTML += `
                <div class="result-item ${isCorrect ? 'correct' : 'incorrect'}">
                    <h4>第${index + 1}题 (${question.score}分)</h4>
                    <p><strong>题目：</strong>${question.question}</p>
                    <p><strong>你的答案：</strong><span class="${isCorrect ? 'correct-answer' : 'user-answer'}">${userAnswer !== null ? question.options[userAnswer] : '未作答'}</span></p>
                    ${!isCorrect ? `<p><strong>正确答案：</strong><span class="correct-answer">${question.options[question.correct]}</span></p>` : ''}
                    <p><strong>解析：</strong>${question.explanation}</p>
                </div>
            `;
        } else if (question.type === 'translation') {
            detailsHTML += `
                <div class="result-item correct">
                    <h4>第${index + 1}题 (${question.score}分) - 翻译题</h4>
                    <p><strong>题目：</strong>${question.question}</p>
                    <p><strong>参考答案：</strong><span class="correct-answer">${question.answer}</span></p>
                    <p><strong>解析：</strong>${question.explanation}</p>
                    <p><em>注：翻译题请根据参考答案自行评分</em></p>
                </div>
            `;
        }
    });
    
    resultDetails.innerHTML = detailsHTML;
}

// 重新进行模拟题练习
function retryPracticeTest() {
    // 隐藏结果页面
    document.getElementById('practice-result').classList.add('hidden');
    
    // 重新开始练习
    startPracticeTest();
}

// 返回文章页面
function backToPracticeArticle() {
    // 停止计时器
    if (practiceTimer) {
        clearInterval(practiceTimer);
        practiceTimer = null;
    }
    
    // 隐藏左右布局页面
    document.getElementById('practice-layout').classList.add('hidden');
    
    // 显示文章页面
    document.getElementById('practice-article').classList.remove('hidden');
}

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
    // 确保只显示选择页面
    document.getElementById('test-selection').classList.remove('hidden');
    document.getElementById('test-progress').classList.add('hidden');
    document.getElementById('test-result').classList.add('hidden');
}); 